#include "log.h"

QFile *gFileLog = NULL;

const char *msgHead[]={
    "Debug   ",
    "Warning ",
    "Critical",
    "Fatal   ",
    "Info    "
};

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    auto msgStr = msg.toStdString();
    auto msgChar = msgStr.c_str();
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");

    if(gFileLog)
    {
        QTextStream tWrite(gFileLog);

        QString msgText="%1 | %2 | %3\n";
        msgText = msgText.arg(msgHead[type], current_date_time, msgChar);
        tWrite << msgText;
    }
    else
    {
        fprintf(stderr, "%s | %s | %s\n", msgHead[type], current_date_time.toLocal8Bit().constData(), msgChar);
    }
}

void logSysInit(const QString &filePath)
{
    gFileLog = new QFile(filePath);
    if(!gFileLog->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        qWarning() << "自定义日志文件失败：" << filePath;
        return;
    }
    //初始化自定义日志处理函数myMessageOutput
    qInstallMessageHandler(myMessageOutput);

}
